package simpleMesh;

import java.awt.geom.Line2D;
import java.util.ArrayList;

import processing.core.PGraphics;
import processing.core.PVector;

public class Triangle extends Face{
	
public Triangle(PVector v1,PVector v2,PVector v3){
	vertices=new ArrayList<PVector>();
	vertices.add(v1);
	vertices.add(v2);
	vertices.add(v3);
}
public Triangle(PVector v1,PVector v2,PVector v3,PVector v4){
	vertices=new ArrayList<PVector>();
	vertices.add(v1);
	vertices.add(v2);
	vertices.add(v3);
	vertices.add(v4);
}

public Triangle(PVector[] vertices){
	for (int i=0;i<vertices.length;i++){
		this.vertices.add(vertices[i]);
	}
}

public PVector getNormal(){
	PVector v=PVector.sub(get(1),get(0));
	PVector u=PVector.sub(get(2),get(0));
	PVector normal=new PVector();
	 PVector.cross(v, u, normal);
	 normal.mult(1f/normal.mag());
	return normal;
}
public void invert(){
	PVector temp=get(0);
	set(0,get(2));
	set(2,temp);
}

public void display(PGraphics g){
	g.beginShape(PGraphics.TRIANGLES);
	for (int i=0;i<vertices.size();i++){
		PVector v=get(i);
		g.vertex(v.x,v.y,v.z);
	}
	g.endShape();
}
public boolean inside2D(float x,float y){
	/*for (int i=0;i<3;i++){
		PVector v1=vertices[i];
		PVector v2=vertices[(i+1)%3];
		double d=Line2D.ptSegDist(v1.x, v1.y, v2.x, v2.y, x, x);
		if (d<0.0001){
			x+=0.01f;
			y+=0.01f;
		}
	}*/
	for (int i=0;i<3;i++){
		PVector v1=get(i);
		PVector v2=get((i+1)%3);
		
		double d=Line2D.ptSegDistSq(v1.x, v1.y, v2.x, v2.y, x, y);
		if (d<0.001){
			
			x+=0.001f;
			y+=0.005f;
		}
		//int res=ONLINE;
		int res=isLeft(v1,v2,x,y);
		/*while (res==ONLINE){
			
			 x+=0.001;
			 y+=0.001;
		}*/
		if (res==RIGHT)return false;
	}
	return true;
}
final static int LEFT=0;
final static int RIGHT=1;
final static int ONLINE=2;
public boolean intersect2D(float x,float y,float z){
	if (!getBounds().contains(x, y))return false;
	if (!underPlane(x,y,z))return false;
	if (!inside2D(x,y))return false;
	return true;
}
public int isLeft(PVector a, PVector b, float x,float y){
	return Line2D.relativeCCW(a.x, a.y, b.x, b.y, x, y);
	/*float d=(b.x - a.x)*(y - a.y) - (b.y - a.y)*(x - a.x);
    if ( d> 0.001) return LEFT;
    if ( d< 0.001) return RIGHT;
   return ONLINE;*/
}
boolean underPlane(float x,float y,float z){
	PVector normal=getNormal();
	float d0=-normal.dot(get(0));
	return normal.dot(x, y, z)+d0<0;
}
}
